<template>
  <div class="map">
    <div id="map-box"></div>
    <div id="panel"></div>

    <div class="serch">
      <f-tabs>
        <f-tab-page id="tab1" title="路线规划">
          <!-- <div> -->
          <!-- <input type="text" v-model="startplace" placeholder="请输入起点" /><br /> -->
          <p class="place pTop">
            <span>起点：</span>
            <el-select
              v-model="startplace"
              placeholder="请输入起点"
              :remote-method="
                (query: any) => {
                  handleSearch(query, 'startData')
                }
              "
              filterable
              remote
              clearable
              :loading="loading"
              :reserve-keyword="false"
            >
              <el-option
                v-for="item in startData"
                :key="item.id"
                :label="item.name"
                :value="item.name + item.address"
              >
                <div class="df jcsb">
                  <span>{{ item.name }}</span>
                  <span style="font-size: 10px; color: var(--el-text-color-secondary)">{{
                    item.address
                  }}</span>
                </div>
              </el-option>
            </el-select>
          </p>

          <!-- <input type="text" v-model="endplace" placeholder="请输入终点点" /><br /> -->
          <p class="place">
            <span>终点：</span>
            <el-select
              v-model="endplace"
              placeholder="请输入终点"
              :remote-method="
                (query: any) => {
                  handleSearch(query, 'endData')
                }
              "
              filterable
              remote
              clearable
              :loading="loading"
              :reserve-keyword="false"
            >
              <el-option
                v-for="item in endData"
                :key="item.id"
                :label="item.name"
                :value="item.name + item.address"
              >
                <div class="df jcsb">
                  <span>{{ item.name }}</span>
                  <span style="font-size: 10px; color: var(--el-text-color-secondary)">{{
                    item.address
                  }}</span>
                </div>
              </el-option>
            </el-select>
          </p>
          <!-- <input type="button" value="查询" @click="serchDiving" /> -->
          <div class="seach-button">
            <f-button :size="'large'" @click="serchDiving"> 查询 </f-button>
          </div>
          <!-- <f-button style="margin: 5px" @click="serchDiving" :size="'large'">查询</f-button> -->
          <!-- </div> -->
        </f-tab-page>
        <f-tab-page id="tab2" title="定位">
          <form>
            <!-- 定位：<input type="text" v-model="geoPlace" placeholder="请输入定位的位置" /><br /> -->
            <!-- <f-combo-list
              v-model="geoPlace"
              :remote="handleSearch"
              :data="data"
              :enableSearch="true"
            ></f-combo-list> -->
            <!-- 终点：<input type="text" v-model="endplace" placeholder="请输入终点点" /><br /> -->
            <!-- <input type="button" value="查询定位" @click="serchGeo" /> -->
            <el-select
              v-model="keyword"
              placeholder="请输入位置进行定位"
              style="padding-top: 10px"
              :remote-method="
                (query: any) => {
                  handleSearch(query, 'data')
                }
              "
              filterable
              remote
              clearable
              :loading="loading"
              :reserve-keyword="false"
            >
              <el-option
                v-for="item in data"
                :key="item.id"
                :label="item.name"
                :value="item.name"
                @click="handleSelect(item)"
              >
                <div class="df jcsb">
                  <span>{{ item.name }}</span>
                  <span style="font-size: 10px; color: var(--el-text-color-secondary)">{{
                    item.address
                  }}</span>
                </div>
              </el-option>
            </el-select>
            <div
              v-show="coord"
              style="font-size: 14px; padding-top: 10px; margin-left: 10px; color: #2a87ff"
            >
              <p>经纬度：{{ coord }}</p>
            </div>
            <!-- <f-text v-model="coord"> </f-text> -->
            <!-- <div style="font-size: 14px">地图mark具体位置信息{{ keyword }}</div> -->
          </form>
        </f-tab-page>
      </f-tabs>
    </div>
  </div>

  <div v-show="isGPS" class="info">
    <h4 id='status'></h4><hr>
    <p id='result'></p><hr>
    <p >由于众多浏览器已不再支持非安全域的定位请求，为保位成功率和精度，请升级您的站点到HTTPS。</p>
</div>
</template>

<script setup lang="ts">
import { shallowRef, ref, nextTick, onMounted, inject } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

const NotifyService: any = inject('NotifyService')
const isGPS = ref(false)

const startplace = ref('')
const endplace = ref('')

let AMapObj: any
let mapDriving: any = shallowRef({})

let driving: any, placeSearch: any, marker: any, geocoder: any

const geoPlace = ref('')
const coord = ref('')
const startData = ref([])
const endData = ref([])
const data = ref([])

const keyword = ref('')

const loading = ref(false)

//解析定位结果
function onComplete(data: any) {
  console.log('onComplete')
  document.getElementById('status').innerHTML = '定位成功'
  var str = []
  str.push('定位结果：' + data.position)
  str.push('定位类别：' + data.location_type)
  if (data.accuracy) {
    str.push('精度：' + data.accuracy + ' 米')
  } //如为IP精确定位结果则没有精度信息
  str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'))
  document.getElementById('result').innerHTML = str.join('<br>')
}
//解析定位错误信息
function onError(data:any) {
  console.log('onError')
  // isGPS.value = true

  // document.getElementById('status').innerHTML = '定位失败'
  // document.getElementById('result').innerHTML = '失败原因排查信息:' + data.message

  NotifyService.show({
      showCloseButton: true,
      timeout: 1000,
      toasts: [{ type: 'string', title: 'GPS定位失败', msg: '失败原因排查信息:' + data.message }]
    })
}

const init = async () => {
  return await new Promise((resolve) => {
    AMapLoader.load({
      key: '49d7eed681d657e0ed754f0464a99ec7', // 设置您的key
      version: '2.0',
      plugins: ['AMap.ToolBar', 'AMap.Driving']
    })
      .then((AMap) => {
        AMapObj = AMap
        console.log('前')

        mapDriving.value = new AMap.Map('map-box', {
          resizeEnable: true
          // zoom: 13,
          // center: [116.397428, 39.90923], // 北京市经纬度
        })

        driving = new AMapObj.Driving({
          map: mapDriving.value,
          panel: 'panel'
        })

        mapDriving.value.on('click', onMapClick)
        AMap.plugin(
          [
            'AMap.ToolBar',
            'AMap.Scale',
            'AMap.Geolocation',
            'AMap.PlaceSearch',
            'AMap.Geocoder',
            'AMap.AutoComplete'
          ],
          () => {
            // 缩放条
            const toolbar = new AMap.ToolBar()
            // 比例尺
            const scale = new AMap.Scale()
            // 定位
            const geolocation = new AMap.Geolocation({
              enableHighAccuracy: true, // 是否使用高精度定位，默认:true
              timeout: 10000, // 超过10秒后停止定位，默认：5s
              position: 'RT', // 定位按钮的停靠位置
              buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
              zoomToAccuracy: true // 定位成功后是否自动调整地图视野到定位点
            })
            geocoder = new AMap.Geocoder({
              city: '全国'
            })
            mapDriving.value.addControl(geolocation)
            geolocation.getCurrentPosition(function (status: string, result: any) {
              console.log('getCurrentPosition')
              // isGPS.value = false
              if (status == 'complete') {
                onComplete(result)
              } else {
                onError(result)
              }
            })

            mapDriving.value.addControl(toolbar)
            mapDriving.value.addControl(scale)
            placeSearch = new AMap.PlaceSearch({
              city: '全国',
              pageSize: 99999999999, // 单页显示结果条数
              pageIndex: 1, // 页码
              citylimit: false, // 是否强制限制在设置的城市内搜索
              autoFitView: true
              // panel: 'list',
              // map: mapDriving.value,
            })
          }
        )

        return resolve(AMapObj)
      })
      .catch((e) => {
        console.log(e)
      })
  })
}

onMounted(async () => {
  // nextTick(async () => {
  await init()
  console.log('后')
})

const serchDiving = () => {
  if (!startplace.value) {
    NotifyService.show({
      showCloseButton: true,
      timeout: 1000,
      toasts: [{ type: 'string', title: '', msg: '请输入起点' }]
    })
    return
  }
  if (!endplace.value) {
    NotifyService.show({
      showCloseButton: true,
      timeout: 1000,
      toasts: [{ type: 'string', title: '', msg: '请输入终点' }]
    })
    return
  }
  AMapObj.plugin('AMap.Driving', function () {
    console.log(startplace.value, endplace.value)
    // driving.clear()
    driving.search([{ keyword: startplace.value }, { keyword: endplace.value }])
  })
}

const serchGeo = () => {
  console.log(123)
  let item = {
    location: {
      lng: 117.24038,
      lat: 29.301516
    }
  }

  drawMarker(item.location)
  if (item.location != null) {
    coord.value = item.location.lng + ',' + item.location.lat
  }
}

// 搜索地图
const handleSearch = (query: any, type: string) => {
  console.log('query', query, type)
  if (query) {
    loading.value = true
    placeSearch.search(query, (status: string, result: any) => {
      console.log(result, status)
      if (status === 'complete' && result.info === 'OK' && result.poiList) {
        loading.value = false
        // debugger
        if (type === 'startData') {
          startData.value = result.poiList.pois
        } else if (type === 'endData') {
          endData.value = result.poiList.pois
        } else {
          data.value = result.poiList.pois
        }
      }
    })
  }
}

//点击搜索选项
const handleSelect = (item: any) => {
  console.log('handleSelect', item)
  drawMarker(item, item.location)
  if (item.location != null) {
    coord.value = item.location.lng + ',' + item.location.lat
  }
}

// 绘制地点marker
const drawMarker = (item: any, location: any) => {
  if (location == null) return
  let longitude = location.lng,
    latitude = location.lat
  if (marker) {
    marker.setMap(null)
  }
  const content = `<div class="custom-content-marker" style="background: #000; padding: 20px">
    <img src="//a.amap.com/jsapi_demos/static/demo-center/icons/dir-via-marker.png">
                    <p>经纬度：${longitude}, ${latitude}</p>
                    <p>位置信息：${item.address}</p>
                  </div>`

  marker = new AMapObj.Marker({
    // content: content, //自定义点标记覆盖物内容
    position: new AMapObj.LngLat(longitude, latitude),
    anchor: 'bottom-center'
  })
  marker.on('click', () => {
    coord.value = location
  })
  mapDriving.value.add(marker)
  mapDriving.value.setZoomAndCenter(16, [longitude, latitude])
}

// 点击地图
const onMapClick = (e: any) => {
  coord.value = e.lnglat.lng + ',' + e.lnglat.lat
  geocoder.getAddress([e.lnglat.lng, e.lnglat.lat], function (status: string, result: any) {
    if (status === 'complete' && result.info === 'OK') {
      // result为对应的地理位置详细信息
      keyword.value = result.regeocode.formattedAddress
    }
  })
  drawMarker(e.lnglat)
}
</script>

<style>
.map,
#map-box {
  height: 100%;
}
.serch {
  position: fixed;
  width: 360px;
  height: 225px;
  z-index: 99;
  top: 20px;
  left: 20px;
  padding: 14px;
  padding-bottom: 68px;
  /* background: #3d93fd; */
  background: #ccc;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
}
.place {
  display: flex;
  align-items: center;
  justify-content: center;
}
.pTop {
  padding-top: 10px;
}
.place > span {
  font-size: 14px;
  color: #5a5e66;
}
.place .el-select {
  display: inline-block;
  width: 80%;
}
.seach-button {
  display: flex;
  align-items: center;
  justify-content: center;
}
.info {
  position: fixed;
  width: 360px;
  height: 225px;
  z-index: 99;
  top: 60px;
  right: 20px;
  padding: 14px;
  padding-bottom: 68px;
  /* background: #3d93fd; */
  background: #fff;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  color: #111213;
}
</style>
